package com.cool4j.generator.service

import com.cool4j.generator.db.ConnectionFactory
import com.cool4j.generator.entity.Table
import com.cool4j.generator.exception.ExceptionMessage
import com.cool4j.generator.util.LogUtil
import com.cool4j.view.entity.HandlerVO

import java.sql.SQLException

/**
 * 获取数据库表结构信息类
 *
 * @author Frank create on 16/1/8 15:40
 */
class TableInfoService {

    /**
     * 获取数据库表结构信息方法
     *
     * @param tableName - 数据库表名
     * @param handlerVO - 界面上设置的配置信息
     * @return - 数据库表结构信息
     */
    Table queryTableInfo(String tableName, HandlerVO handlerVO) {
        def connection = ConnectionFactory.driver(handlerVO.getDriver()).connection()
        def username = handlerVO.getUsername()
        def table
        def columnList = []
        def conn

        try {
            conn = connection.getConnection(username, handlerVO.getPassword(), handlerVO.getDriver(), handlerVO.getUrl())
        } catch (Exception e) {
            LogUtil.logging(ExceptionMessage.EXCEPTION_GET_CONNECTION, e)
        }
        if (conn != null) {
            try {
                table = connection.getTable(conn, tableName)
            } catch (Exception e) {
                LogUtil.logging(ExceptionMessage.EXCEPTION_GET_TABLE_INFO, e)
            }
            try {
                columnList = connection.getColumnList(conn, tableName, username)
            } catch (Exception e) {
                LogUtil.logging(ExceptionMessage.EXCEPTION_GET_COLUMN_INFO, e)
            }
            if (table != null && columnList != null) {
                table.setColumnList columnList
            }
        }
        try {
            if (conn != null) {
                conn.close()
                conn = null
            }
        } catch (SQLException e) {
            LogUtil.logging(ExceptionMessage.EXCEPTION_CLOSE_CONNECTION, e)
        }
        return table
    }

}
